package com.huahua.shard.myShard;


import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

public class USerTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        try {
            String tableName = preciseShardingValue.getLogicTableName();
            String dataTime;
            if (preciseShardingValue.getValue() != null) {
                dataTime = formatter.format(preciseShardingValue.getValue());
            } else {
                throw new IllegalArgumentException("没有匹配到库");
            }
            // 按照月份，拼接数据库表名
            return tableName.concat("_").concat(dataTime.substring(5, 7));
        } catch (Exception e) {
            throw new IllegalArgumentException("没有匹配到库:" + preciseShardingValue.getValue());
        }
    }
}